<?php


namespace App\Admin\Forms\Site;


use App\Models\Config\SystemConfig;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;

class HomeConfig extends Form implements LazyRenderable
{
    use LazyWidget;

    public static function label() :array
    {
        return [
            "name"=>"网站名称",
            "url"=>"网站地址",
            "asset_url"=>"资源地址",
            "timezone"=>"时区设置",
            "debug"=>"开启调试",
            "locale"=>"语言",
            "icp" => "备案号"
        ];
    }


    public static function mapping() :array
    {
        return [
            "name" => "app.name",
            "url" => "app.url",
            "asset_url" => "app.asset_url",
            "timezone" => "app.timezone",
            "debug" => "app.debug",
            "locale" => "app.locale",
            "icp" => "site.icp"
        ];
    }

    /**
     * 构建表单.
     */
    public function form()
    {
        $label = static::label();
        $this->text('name',Arr::get($label,"name"))->required();
        $this->url('url',Arr::get($label,"url"))->required();
        $this->url('asset_url',Arr::get($label,"asset_url"));
        $this->radio('timezone', Arr::get($label,"timezone"))->required()->options(['PRC' => 'PRC', 'UTC' => 'UTC']);
        $this->radio('debug', Arr::get($label,"debug"))->required()->options(['0' => '关闭', '1' => '开启']);
        $this->radio('locale', Arr::get($label,"locale"))->required()->options(['en' => 'English', 'zh_CN' => '简体中文']);
        $this->divider();
        $this->text('icp',Arr::get($label,"icp"));
    }

    /**
     * 处理表单的提交
     * @param array $input
     * @return \Dcat\Admin\Http\JsonResponse
     */
    public function handle(array $input)
    {
        $labels = static::label();
        $fields = static::mapping();
        foreach ($fields as $key => $value){
            SystemConfig::updateOrCreate(["key"=>$value],["name" => Arr::get($labels,$key), "value" => Arr::get($input,$key)]);
        }

        return $this->response()->success('设置成功');
    }

    /**
     * 表单默认值
     * @return mixed
     */
    public function default()
    {
        $keys = static::mapping();
        $all = SystemConfig::whereIn("key",array_values($keys))->pluck("value","key");
        foreach ($keys as &$key){
            $key = Arr::get($all,$key);
        }
        return $keys;
    }


    public function savedScript()
    {
        return <<<'JS'
    if (data.status) {
        setTimeout(function () {
          location.reload()
        }, 1200);
    }
JS;
    }
}
